package com.behome.netty.netty_D.handler;

import com.behome.netty.netty_B.bean.ReBackPacket;
import com.behome.netty.netty_B.handler.BusinessBHandlerBase;
import com.behome.netty.netty_D.bean.Packet;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

@Slf4j
public class BusinessDHandlerFactory {

    public BusinessDHandlerFactory() {
    }

    public static BusinessDHandlerBase createBusinessHandler(ChannelHandlerContext ctx, Packet msg, String businessHandlerPackageName, int type) {
        if (ctx != null && msg != null && msg.getBody() != null && msg.getBody().getBusinessCmd() != null) {
            if (StringUtils.isBlank(businessHandlerPackageName)) {
                return null;
            } else {
                String busiCmdStr = msg.getBody().getBusinessCmd().getClass().getSimpleName();
                String handlerClassStr = businessHandlerPackageName + "." + busiCmdStr + "Handler";
                BusinessDHandlerBase handler = null;
                try {
                    Constructor<?> constructor = Class.forName(handlerClassStr).getConstructor(ChannelHandlerContext.class, Packet.class, int.class);
                    handler = (BusinessDHandlerBase) constructor.newInstance(new Object[]{ctx, msg, type});
                } catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException |
                         IllegalArgumentException | InvocationTargetException var7) {
                    log.error("构造业务处理器时发生错误.", var7);
                } catch (ClassNotFoundException var9) {
                    log.warn("尚未提供名称为" + handlerClassStr + "的处理器来处理类型为" + busiCmdStr + "的业务指令.");
                }
                return handler;
            }
        } else {
            return null;
        }
    }
}